#!/usr/bin/env python
#
#This module focuses on GUI and Widget classes
#
import re
import os
import sys 
from PyQt4.QtCore import * 
from PyQt4.QtGui import * 
 
#Function

def getShiftTime(t):
	return re.split("[-]",t)

#creat a data structure for shifts?
class ShiftDS(list):
	day = None
	start = None
	end = None
	location = None
	pay = None

        def getTableLine(self):
                "Return table formated line"
                r = self.day + '\t' 
                r += self.start + '-' + self.end + '\t' 
                r += self.location + '\t' + self.pay + '\n' 
                return r
                

class ShiftDat():
	#List of shifts
	shift = ShiftDS()
        Header = []
	def importTable(self, table):
		"Imports data from read in table"
		pass
                i=0
                tmp = ShiftDS()
                for r in table:
                        #Might need a better error detection in case of manual edit
                        #for now just skip broken lines
                        if len(r)<4:
                                continue

                        #Skip heading (hack)
                        if r[0]=='Date':
                                self.Header = r
                                continue

                        tmp.day = r[0]
                        t = re.split("[-]", r[1])
                        tmp.start = t[0]
                        tmp.end = t[1]
                        tmp.location = r[2]
                        tmp.pay = r[3]
                        self.shift.append(tmp)

        def saveTable(self, FileName):
                print ">> list len ", len(self.shift)
                for r in self.shift:
                        print ">>> ", r 

                "Saves the data as plain table"
                f = open(FileName, 'w')
                #Header
                h=''
                for H in self.Header:
                        h += H + '\t' 
                h=h[0:-1] + '\n'
                f.write(h)

#help! This bit is wrong!
                R=ShiftDS()
                for R in self.shift:
                        f.write(R.getTableLine())

                f.close()
		

	#add, find, edit, save


def main(): 
    app = QApplication(sys.argv) 
    w = MyWindow() 
    w.show() 
    sys.exit(app.exec_()) 


class MyWindow(QWidget): 
    def __init__(self, *args): 
        QWidget.__init__(self, *args) 

	#Set up tabbed interface
	Tab_Widget = QTabWidget()
	EntryTab	= QWidget()
	SummaryTab	= QWidget()
	SettingsTab	= QWidget()
	Tab_Widget.addTab(EntryTab, 	'Entry')
	Tab_Widget.addTab(SummaryTab, 	'Summary')
	Tab_Widget.addTab(SettingsTab, 	'Settings')

        # create table
        self.get_table_data()
        table = self.createTable() 
        S = ShiftDat()
        S.importTable(self.tabledata)
        S.saveTable('misc/output.txt')

	#Entry dialog	
	ShiftLabel=QLabel('Shift:')
	DateEdit = QDateEdit()
	TimeEdit = QTimeEdit()
	LocationBox = QComboBox()
	PayBox = QComboBox()
	#Fill comboxes; note: later fill from settings page
	LocationBox.addItem('Library')
	LocationBox.addItem('F&D Top Floor')
	LocationBox.addItem('F&D Restaurant')
	PayBox.addItem('PAY')
	PayBox.addItem('TOIL')
	#Assemble the form in a hor line
	EntryLayout = QHBoxLayout(EntryTab)
	#EntryLayout.addWidget(ShiftLabel)
	#EntryLayout.addWidget(DateEdit)
	#EntryLayout.addWidget(TimeEdit)
	#EntryLayout.addWidget(LocationBox)
	#EntryLayout.addWidget(PayBox)

	#Shift display box: label+button
	ShiftBox = QHBoxLayout()
	ShiftTime = getShiftTime('13:00-17:00')
	ShiftFromLabel = QLabel(ShiftTime[0])
	ShiftToLabel = QLabel(ShiftTime[1])
	ShiftCloseBtn = QPushButton('x')
	ShiftBox.addWidget(ShiftFromLabel)
	ShiftBox.addWidget(ShiftToLabel)
	ShiftBox.addWidget(ShiftCloseBtn)
	EntryLayout.addLayout(ShiftBox)
	#End of entry dialog

	#Summary display
	SummaryLayout = QBoxLayout(QBoxLayout.TopToBottom, SummaryTab)
	ToilHbox = QHBoxLayout()
	ToilL = QLabel('TOIL')
	ToilLeftL = QLabel('Left: 0h')
	ToilEarnedL = QLabel('Earned: 4h')
	ToilSpentL = QLabel('Spent: 4h')
	ToilHbox.addWidget(ToilL)
	ToilHbox.addWidget(ToilLeftL)
	ToilHbox.addWidget(ToilEarnedL)
	ToilHbox.addWidget(ToilSpentL)

	PayHbox = QHBoxLayout()
	PayL = QLabel('PAY ')
	PayTotalL = QLabel('Total: 500')
	PayHbox.addWidget(PayL)
	PayHbox.addWidget(PayTotalL)
	SummaryLayout.addLayout(ToilHbox)
	SummaryLayout.addLayout(PayHbox)


        # layout
        DataLayout = QVBoxLayout()
        #DataLayout.addWidget(table) 
        SummaryLayout.addWidget(table) 
	
	pl=QBoxLayout(QBoxLayout.TopToBottom)
	pl.addWidget(Tab_Widget)
	#pl.addLayout(DataLayout)
	#pl.addLayout(EntryLayout)

	#Assign the layout to MyWindow
        self.setLayout(pl) 
	
    def get_table_data(self):
	"Reads in the data from a file"
	f = open('misc/input.txt', 'r')
	fdata = f.read()
	f.close()
	fdata = re.split('\n', fdata)
	ftable=[]
	for line in fdata:
	        ftable.append( re.split('\t', line) )
	self.tabledata = ftable 

    def createTable(self):
        # create the view
        tv = QTableView()

        # set the table model
        header = self.tabledata[0] 
        tm = MyTableModel(self.tabledata[1:len(self.tabledata)-1], header, self) 
        tv.setModel(tm)

        # set the minimum size
        self.setMinimumSize(400, 300)

        # hide grid
        tv.setShowGrid(False)

        # set the font
        font = QFont("Courier New", 8)
        tv.setFont(font)

        # hide vertical header
        vh = tv.verticalHeader()
        vh.setVisible(False)

        # set horizontal header properties
        hh = tv.horizontalHeader()
        hh.setStretchLastSection(True)

        # set column width to fit contents
        tv.resizeColumnsToContents()

        # set row height
        nrows = len(self.tabledata)
        for row in xrange(nrows):
            tv.setRowHeight(row, 18)

        # enable sorting
        # this doesn't work
        #tv.setSortingEnabled(True)

        return tv
 
	class ShiftDisplay(QWidget):
		"Display shifts"
		def __init__(self, parent):
			QWidget.__init__(self, parent)
	
		#label+button
		ShiftBox = QHBoxLayout()
		ShiftLabel = QLabel('from-to')
		ShiftCloseBtn = QPushButton('x')
		ShiftBox.addWidget(ShiftLabel)
		ShiftBox.addWidget(ShiftCloseBtn)

class MyTableModel(QAbstractTableModel): 
    def __init__(self, datain, headerdata, parent=None, *args): 
        QAbstractTableModel.__init__(self, parent, *args) 
        self.arraydata = datain
        self.headerdata = headerdata
 
    def rowCount(self, parent): 
        return len(self.arraydata) 
 
    def columnCount(self, parent): 
        return len(self.arraydata[0]) 
 
    def data(self, index, role): 
        if not index.isValid(): 
            return QVariant() 
        elif role != Qt.DisplayRole: 
            return QVariant() 
        return QVariant(self.arraydata[index.row()][index.column()]) 

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return QVariant(self.headerdata[col])
        return QVariant()

if __name__ == "__main__": 
    main()

